import React, {useEffect, useState, memo} from 'react';
import { Button, Col, message, Row, Spin, Transfer} from "antd";
import {findAllUrls, UpdateUrlByUserId, getUrlsByUserId} from "../../../../api/list"


function EditUrls(props) {
    const {id} = props
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [targetKeys, setTargetKeys] = useState([]);
    const onChange = (newTargetKeys) => {
        setTargetKeys(newTargetKeys);
    };
    const saveUrls = async () => {
        setLoading(true)
        const newUrls = JSON.stringify(targetKeys)
        const {data: res} = await UpdateUrlByUserId({id: id * 1, urls: newUrls.substring(1, newUrls.length - 1)})
        message.success(res['msg'])
        setLoading(false)
    }
    useEffect(() => {
        setLoading(true)
        async function getUrls() {
            const {data: res} = await findAllUrls()
            return res.data
        }

        async function getCurrentUrls() {
            const {data: res} = await getUrlsByUserId(id)
            return res.data
        }

        getUrls().then(response => {
            let newData = []
            response.forEach(url => {
                newData.push({
                    id: url['id'],
                    title: url['detail'],
                    description: url['url']
                })
            })
            setData(newData)
        })
        getCurrentUrls().then(urls => {
            setTargetKeys(JSON.parse(`[${urls}]`))
        })
        setTimeout(()=>{
            setLoading(false)
        },800)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [id])
    return (
        <Spin tip={'加载中...'} spinning={loading}>
            <Transfer
                rowKey={record => record.id}
                dataSource={data}
                targetKeys={targetKeys}
                onChange={onChange}
                render={item => item.title}
                pagination
                showSearch
                style={{padding:'0 5vh 0 5vh'}}
            />
            <Row>
                <Col span={16}></Col>
                <Col span={8} style={{
                    textAlign: 'right',
                }}><Button type="primary" onClick={saveUrls} loading={loading}>保存</Button></Col>
            </Row>
        </Spin>
    );
}

export default memo(EditUrls);